require "api_cms_helpers"

module GrapeAPI
  module CMS
    class ManagementCms < Grape::API
      version "cms"
      # prefix "v1"
      format :json

      helpers GrapeAPI::APICmsHelpers

      # rescue_from :all do |e|
      # Rack::Response.new([ e.message ], 500, { "Content-type" => "text/error" }).finish
      # end

      resource :UsersManagementPage do
        get do
          page_limit = params["page_limit"]
          user_info = {}
          user_count = User.count
          users = User.all
          # users = User.limit(page_limit).offset(0).order("id ASC")
          user_list = format_user(users)
          user_info["user_count"] = user_count
          user_info["user_list"] = user_list
          user_info
        end

        get '/deluser' do
          user_type = params['command_type']
          user_id = params['user_id']
          status = false

          begin
            User.transaction do
              if user_type.to_s == "del_all"
                user_id.split(',').each do |u_id|
                  user = User.find(u_id.to_i)
                  unless user.blank?
                  user.destroy
                  end
                end
              status = true
              else
                user = User.find(user_id.to_i)
                unless user.blank?
                user.destroy
                status = true
                end
              end
            end
          end

          {:status => status}
        end
        put do
          username = params["username"]
          pwd = params["pwd"]
          user = User.where(:username => username).first
          unless user.blank?
            if user.valid_password?(pwd)
              user.authentication_token = User.get_token
              user.save
              
              {:token => user.authentication_token, :status => 200}
            else
              {:token => "",:status => 401}
            end
          else
            {:token => "", :status => 500}
          end
        end
      end

      resource :devappsManagement do
        get do
          app_infos = {}
          baas_apps = BApp.all
          app_list = format_apps(baas_apps) unless baas_apps.blank?
          app_infos["app_list"] = app_list

          app_infos
        end

        get "/delapps" do
          app_id = params['app_id']
          app_type = params['command_type']
          status = false
          begin
            BApp.transaction do
              if app_type.to_s == "del_all"
                app_id.split(',').each do |ap_id|
                  app = BApp.find_by(:app_id => ap_id.to_s)
                  unless app.blank?
                  app.destroy
                  status = true
                  end
                end
              else
                app = BApp.find_by(:app_id => app_id.to_s)
                unless app.blank?
                app.destroy
                status = true
                end
              end
            end
          rescue
          end

          {:status => status}
        end
      end
     resource :app_info do
       get do
         app_id = params["app_id"]
         app_master_key = nil
         app = BApp.find_by(:app_id => app_id.to_s)
         unless app.blank?
           app_master_key = app.app_master_key.to_s
         end
         {:app_master_key => app_master_key}
       end
     end
     
     resource :roles_management do
       get do
        roles_list = []
        roles = Role.all.select(:id, :name, :resource_id, :resource_type)
        roles.each do |role|
          roles_permissions = {}
          roles_permissions["roles"] = role
          permissions = role.roles_permissions 
          roles_permissions["roles_permissions"] = permissions  unless permissions.blank?
          roles_list << roles_permissions
        end
        {:roles_list => roles_list}
       end
       post  do
         
       end
       put do
         request = params.to_hash
         role_name = request["role_name"]
         role_perssion = request["role_perssion"]
         role_perssion_des = request["role_perssion_des"]
         @user = User.find_by(:email=>"douchunrong@gmail.com", :username => "douchunrong") unless role_name.blank?
         if @user
           role = @user.add_role( role_name )
           role.roles_permissions << RolesPermission.new(:action_name =>role_perssion, :description => role_perssion_des )
         end
         #向相关网站发送更改信息
         urls = site_conf("server_path")
         urls.each do |url|
           patd = url + "api/v1/cms/roles_management"
           http_put(url, params)
         end
         
         
         {:status => 200}
       end
       delete do
         
       end
     end
     resource :roles_users_management do
       get do
        users = User.all
        roles_users = {}
        users.each do |user|
          roles_users[user.email.to_s] = user.roles_name
        end
        {:roles_users_list => roles_users}
       end
       get "/detial" do
         request = params
         email = request["id"]
         user = nil
         user_roles = nil
         roles_list = nil
         user_info = {}
         
         
         user = User.find_by(:email => email) unless email.blank?
         unless user.nil?
           user_roles = user.roles_name
           roles_list =  Role.all.select(:id, :name, :resource_id, :resource_type)
         end
         
         {:user_info =>user, :user_roles => user_roles, :roles_list => roles_list}
       end
       post  do
         
       end
       put do
         
         request = params.to_hash
         user_id = request["id"]
         roles = request["paramater"]
         user = User.find_by(:id=>user_id)
         new_role = []
         unless user.blank?
           current_role = user.roles_name
           #判断 删除还是添加
           new_role = current_role - roles
           if new_role.size > 0
               new_role.each do |role|
                 user.remove_role role
               end
           else
               new_role = roles - current_role
               new_role.each do |role|
                 user.add_role role
               end if new_role.size > 0
           end
         end
         
         {:status => 200}
       end
       delete do
         
       end
     end
     #=====激活=======#
     resource :activeself do
       post do
         _activation_code = params["activation_code"]
         _login = params["login"]
         User.find_and_activate!(_login, params[:activation_code])
         response_format!
       end
     end
     #====删除自己====#
     resource :delself do
       post do
         _user_id = params["user_id"]
         user = User.find(_user_id)
         if user
           # user.user_confirms.each do |uc|
             # uc.destroy
           # end
           user.destroy
         end
         response_format!
       end
     end
     #==end==#
    end
  end
end